package com.wuyan.web.base.api.view;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wuyan.web.base.aop.ApiLogAnnotation;
import com.wuyan.web.base.entity.PubAccount;
import com.wuyan.web.base.entity.PubUser;
import com.wuyan.web.base.form.pojo.PubViewAccountPOJO;
import com.wuyan.web.base.helper.BaseApi;
import com.wuyan.web.base.helper.SpringRedisHelper;
import com.wuyan.web.base.helper.auth.LoginInfo;
import com.wuyan.web.base.helper.rep.RepBody;
import com.wuyan.web.base.helper.rep.RepHelper;
import com.wuyan.web.base.repo.PubAccountRepo;
import com.wuyan.web.base.repo.PubUserRepoExtend;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 扩展接口
 */

@Slf4j
@RestController
@RequestMapping("/api/pub-view-account")
public class PubViewAccountApiExtend extends BaseApi implements RepHelper {
    private static final String SESSION_AUTH_LOGIN_NAME = "auth-login";

    @Autowired
    private PubAccountRepo pubAccountRepo;

    @Autowired
    private PubUserRepoExtend pubUserRepoExtend;

    @Autowired
    private ObjectMapper mapper;

    @Autowired
    private SpringRedisHelper springRedisHelper;

    /**
     * 修改当前账户的个人信息
     *
     * @param request            请求体
     * @param pubViewAccountPOJO 数据
     * @return RepBody<PubViewAccount>
     */
    @PutMapping("/info")
    @ApiLogAnnotation(name = "PubMsg:updateInfo")
    @Transactional(rollbackFor = Exception.class)
    public RepBody<LoginInfo> updateInfo(HttpServletRequest request,
                                              @RequestBody @Validated PubViewAccountPOJO pubViewAccountPOJO)
            throws Exception {
        LoginInfo loginInfo = getLoginInfo(request);

        PubAccount account = loginInfo.getAccount();
        PubUser user = loginInfo.getUser();

        BeanUtils.copyProperties(pubViewAccountPOJO, account);
        BeanUtils.copyProperties(pubViewAccountPOJO, user);

        pubAccountRepo.save(account);
        pubUserRepoExtend.save(user);

        request.getSession().setAttribute(SESSION_AUTH_LOGIN_NAME,
                mapper.writeValueAsString(loginInfo));

        springRedisHelper.set(loginInfo.getToken(),
                mapper.writeValueAsString(loginInfo),
                loginInfo.getExpiresIn());

        return ok(loginInfo);
    }
}